//评论类
function Comment(option){
	var option = option || {};
	this.getCommentUrl = option.getCommentUrl || '/btcomment/';
	this.setCommentUrl = option.setCommentUrl || '/btcomment/';
	this.commentForm = option.commentForm || $('#comment-form');
	this.commentMask = option.commentMask || $('#comment-mask');
	this.commentCount = option.commentCount || $(".comment-count i");
	this.commentList = option.commentList || $('#comments-list');
	this.loading = option.loading || $(".loading");

	this.commentTextArea = this.commentForm.find('textarea');
	this._init();
}

Comment.prototype = {
	_init : function(){
		var _self = this;

        this.commentList.on('click', 'li', this._cancelDelete());

        this.commentList.on('swipe', 'li', this._readyToDelete());

        this.commentMask.on('click', this.readyToComment());

        
        this.commentTextArea.on('focus', function(e){
        	_self.commentMask.hide();
	        _self.commentTextArea.focus();
        });

        this.commentForm.on('submit', this.postComment());
        this.commentList.on('click', '.reply', this.replyComment());
        this.commentList.on('click', '.delete', this.deleteComment());
      
 	},
	deleteComment: function(){
		_self = this;
        return function(e){
            e.preventDefault();
            if ( BT.context('is_staff') ) {
                result = window.confirm('这么就删除了？');
                if ( !result ) {
                    return false;
                }
            }
	        var _li = $(this).parents('li'),
	        	_id = _li.data('cid');
	        $.ajax({
	            url: _self.setCommentUrl,
	            type: 'POST',
	            dataType: 'json',
	            data: {
	                operator: 'delete',
	                csrfmiddlewaretoken: BT.context('csrf_token'),
	                id: _id
	            },
	            success: function (data) {
	                if ( data.success ) {
	                    $(_li).fadeOut('500');
	                    _self._modifyCount( -1 );
	                }else{
	                    alert(data.errmsg);
	                }
	            }
	        });
		}
	},
	postComment : function(){
		var _self = this;
		return function(e){
			e.preventDefault();
	        var _data = $(this).serializeArray();
	        _data[4].value = encodeHTML(_data[4].value);
	        $.ajax({
	            url: _self.setCommentUrl,
	            type: 'POST',
	            dataType: 'json',
	            data: _data,
	            success: function (data) {
	                if ( data.success ) {
	                    _self.commentForm.find('textarea').val('');
	                    
	                    $(_self._buildCommentHtml(data.comment)).prependTo(_self.commentList);

	                    _self._modifyCount( 1 );
	                    _self.commentForm.find('input[name="reply_to_comment_id"]').val('');
	                }
	            }
	        });
		}

	},
	replyComment : function(){
		var _self = this;
		return function(e){
			e.preventDefault();
			if(BT.context('user_id') == 0){
				btAppSchema.jumpToLogin(window.location.href);
			}else{
				var parent = $(this).parents('li');
		        var _name = parent.find('.comment-username').html();
		        	comment_id = parent.data('cid');
		        _self.commentTextArea.focus().val('回复'+_name+'：');
		        _self.commentForm.find('input[name="reply_to_comment_id"]').val(comment_id);
		        _self.commentTextArea.focus();
			}
		}
		
	},
	readyToComment : function(){
		var _self = this;
		return function(e){
			if(BT.context('user_id') == 0){
				btAppSchema.jumpToLogin(window.location.href);
			}else{
				$(window).scrollTop( _self.commentForm.parent().parent().offset().top -50);
				_self.commentTextArea.val('').focus();
			}
		}
	},
	_cancelDelete: function(){
		return function(e){
			$(this).find('.delete').removeClass('show');
		};
		
	},
	_readyToDelete: function(e){
		return function(e){
			$(this).find('.delete').addClass('show');
		}
	},
	_modifyCount : function(count){
		var commentCount = this.commentCount;
	    var num = parseInt( commentCount.text() ) + count;
	    commentCount.text(num);
	},
	_loadMoreComments : function(){
		var _self = this;
		this.loadHandeler = this.loadHandeler || function(e){
			var reachBottom = document.body.scrollTop + window.innerHeight >= $(document).height() - 200;
	        if ( reachBottom ) {
	        	$(document).off('scroll',_self._loadMoreComments());
	            _self.getComments();
	        }
		}
		return this.loadHandeler;
	},
	getComments : function(){
		var _self = this;
        $.ajax({
            url: _self.getCommentUrl,
            type: 'GET',
            dataType: 'json',
            data: {
                'uri': BT.context('bt_comment_uri'),
                'count': 10,
            },
            success: function (data) {
                if ( data.success ) {
                    _self.getCommentUrl = data.next_page_url;
                    _self.commentCount.text(data.total);
                    $.each(data.comments, function(index, val) {
                
                        $(_self._buildCommentHtml(val)).appendTo(_self.commentList);
                    });
                    if ( data.has_more ) {
                        $(document).on('scroll', _self._loadMoreComments());
                    }else{
                    	$(document).off('scroll',_self._loadMoreComments());
                        _self.loading.text("没有更多评论");
                    }
                }
            },
        });
	},
	_buildCommentHtml : function(comment){
		var html = [
			'<li class="clearfix" data-cid="'+comment.comment_id+'">',
        		'<a href="javascript:btAppSchema.jumpToUser('+comment.user_id+', \''+comment.username+'\');" class="m-avatar">',
					'<img src="'+comment.user_avatar+'">',
				'</a>',
                ( BT.context('user_id') == comment.user_id || BT.context('is_staff') ? '<span class="delete">X</span>' : '' ),
                ( BT.context('user_id') == comment.user_id ? '' : '<span class="reply">回复</span>' ),
				'<div class="comment-info">',
					'<a class="comment-username" href="javascript:btAppSchema.jumpToUser('+comment.user_id+', \''+comment.username+'\');">'+comment.username+'</a>',
					'<span>'+comment.date_added+'</span>',
					'<p>'+comment.comment+'</p>',
				'</div>',
			'</li>'
		];
		return html.join('');
	}
}
function encodeHTML(source) {                                                                                                                
    return String(source)
        .replace(/&/g,'&amp;')
        .replace(/</g,'&lt;')
        .replace(/>/g,'&gt;')
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
};

window.BT = window.BT || {};
BT.Comment = Comment;